package com.wangsai.framework.supersecurity.servlet;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.wangsai.framework.supersecurity.core.SuperSecurityManager;
import com.wangsai.framework.supersecurity.core.UserRequest;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilter;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilterChain;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.Wang
 * @date 2021-08-15 22:30
 */
@Slf4j
@Component
public class ServletUserContextFilter implements UserContextFilter {

    @Override
    public void doFilter(UserRequest userRequest, UserContextFilterChain filterChain) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!userRequest.isHasUser() && requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            String userMetadata = request.getHeader(SuperSecurityManager.getConfig().getUserKey());
            if (StringUtils.isNotBlank(userMetadata)) {
                try {
                    JSONObject jsonObject = JSON.parseObject(SuperSecurityManager.getUserSecure().decode(userMetadata));
                    for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                        if (entry.getValue() == null) {
                            continue;
                        }
                        userRequest.getUser().put(entry.getKey(), entry.getValue());
                    }
                    userRequest.setHasUser(true);
                } catch (ClassCastException exception) {
                    log.warn("用户类型转换出错");
                }
            }
        }
        filterChain.doFilter(userRequest, filterChain);
    }

}